<?php
namespace app\user\controller;
use app\common\model\Comment;
use app\common\model\Express;
use app\common\model\Renovation as MerchantModel;
use app\common\model\Comment as CommentModel;
use think\Exception;
use think\facade\Session;
use think\db;


/**
 * 订单操作控制器
 * Class Operate
 * @package app\user\controller\order
 */
class Renovation extends Controller
{
    /* @var OrderModel $model */
    private $model;

    private $delete_type = [1=>'未审核',2=>'审核通过',3=>'审核不通过',4=>'已删除',5=>'休息中'];


    /**
     * 商铺详情
     * @param $order_id
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function shoudetail($merchant_id,$type)
    {
        $model = new MerchantModel;
        $delete_type = $this->delete_type;
        $detail=$model::shoudetail($merchant_id);
        $where = [];$wherea=[];$whereb=[];
        $where['province_id'] = $detail['province_id'];
        $province = $model->citylist($where);
        !empty($province)?$detail['provincename'] = $province['name']:$detail['provincename']='';
        $wherea['city_id'] = $detail['city_id'];
        $citylist = $model->citylist($wherea);
        !empty($citylist)?$detail['cityname'] = $citylist['name']:$detail['cityname']='';
        $whereb['district_id'] = $detail['district_id'];
        $district = $model->citylist($whereb);
        !empty($district)?$detail['districtname'] = $district['name']:$detail['districtname'] ='';
        return $this->fetch($type,compact('detail','delete_type'));

    }

    /**
     * 装修商列表
     */
    public function renovation($name = '')
    {
        $info =$this->request->post();
        $houtai = Session::get('houtaizhuangtai');
        if(!empty($houtai)&&$houtai ==1){
            $model = new MerchantModel;
            $where['merchant_user_id'] = Session::get('wymall_store.user_id');
            $where['state'] = '1';
            $merchant = $model->zhanghaodan($where);
            $type = 'renovationdetail';
            $delete_type = $this->delete_type;
            $detail=$model::shoudetail($merchant['merchant_id']);
            $where = [];$wherea=[];$whereb=[];
            $where['province_id'] = $detail['province_id'];
            $province = $model->citylist($where);
            !empty($province)?$detail['provincename'] = $province['name']:$detail['provincename']='';
            $wherea['city_id'] = $detail['city_id'];
            $citylist = $model->citylist($wherea);
            !empty($citylist)?$detail['cityname'] = $citylist['name']:$detail['cityname']='';
            $whereb['district_id'] = $detail['district_id'];
            $district = $model->citylist($whereb);
            !empty($district)?$detail['districtname'] = $district['name']:$detail['districtname'] ='';
            return $this->fetch($type,compact('detail','delete_type'));
        }
        $delete_type = $this->delete_type;
        $model = new MerchantModel;
        $list = $model->getlist($this->request->post(),'1');
        if(count($list)>0)
        {
            foreach ($list as $key=>$value)
            {
                $where = [];$wherea=[];$whereb=[];
                $where['province_id'] = $value['province_id'];
                $province = $model->citylist($where);
                !empty($province)?$list[$key]['provincename'] = $province['name']:$list[$key]['provincename']='';
                $wherea['city_id'] = $value['city_id'];
                $citylist = $model->citylist($wherea);
                !empty($citylist)?$list[$key]['cityname'] = $citylist['name']:$list[$key]['cityname']='';
                $whereb['district_id'] = $value['district_id'];
                $district = $model->citylist($whereb);
                !empty($district)?$list[$key]['districtname'] = $district['name']:$list[$key]['districtname'] ='';

            }
        }
        return $this->fetch('renovationlist', compact('list','delete_type'));
    }


    public function initialize()
    {
        parent::initialize();
        $this->model = new MerchantModel;
    }
    /**
     * 导出
     * @param string $dataType
     * @throws \think\exception\DbException
     */
    public function export($dataType)
    {	
        return $this->model->exportList($dataType, $this->request->get());
    }
    /**
     * 批量
     */
    public function deliveryTpl()
    {
        return $this->model->deliveryTpl();
    }

    /**
     * 删除数据
     * @param $id
     * @param $table
     * @return array
     */
    public function uptatead($id='',$table='1')
    {

        if(!empty($id)){
            $model = new MerchantModel;
            if($table == 'uptatead'){
                $table = '2';
            }
            if($table == 'uptatecd'){
                $table = '3';
            }
            if($table == 'deletead'){
                $table = '4';
            }
            if($table == 'deletecd'){
                $table = '2';
            }
            $info = $model->saveMerchant($id,$table);
            if($info){
                return $this->renderSuccess('修改成功');
            }
            return $this->renderError($model->getError() ?: '修改失败');
        }
    }

    /**
     * 商品列表(出售中)
     */
    public function items($status = null, $category_id = null, $name = '', $market = '')
    {
        // 商品分类
        //$catgory = (new CategoryModel)->getSortCategory();
        $catgory= '';
        // 商品列表
        $model = new \app\common\model\Item();
        $state = 1;
        $list = $model->pcgetList($state,$status, $category_id, $name,$market);
        if(count($list)>0)
        {$model2= new MerchantModel;
            foreach ($list as $key=>$value)
            {
                $whereb=[];
                $whereb['district_id'] = $value['district_id'];
                $district = $model2->citylist($whereb);
                !empty($district)?$list[$key]['districtname'] = $district['name']:$list[$key]['districtname'] ='';

            }
        }
        /*if(count($list['data'])>0){
            foreach ($list['data'] as $key=>$vavel){
                $list['data'][$key]['create_timead'] = date('Y-m-d H:i',$vavel['create_time']);
            }
        }*/

        if(empty($market)){
            return $this->fetch('index', compact('list'));
        }
        return $this->fetch('goodslist', compact('list'));
    }

    /**
     * 商品编辑
     */
    public function pcedit($goods_id='')
    {
        $model = new \app\common\model\Item();
        $data=$this->request->post();
        $state = '1';
        if (!$this->request->isAjax()) {
            $goodsInfo=$model::pcdetailad($goods_id);
            $arr_imge = $model::detailimg($goods_id);
            // 商品分类
            /*  $itemType = (new TypeModel)->All();
             $brandList = (new ItemModel)->getSortBrands();//获取品牌
             $delivery = DeliveryModel::getAll();*/
            //sku和分类
            $province = $model->provinceList();
            $citylist = '';
            if(!empty($goodsInfo['province_id'])){
                $citylist = $model->cityList($goodsInfo['province_id']);
            }
            $dislist='';
            if(!empty($goodsInfo['city_id'])){
                $dislist = $model->districtList($goodsInfo['city_id']);
            }

            return $this->fetch('edit', compact('goodsInfo','arr_imge','province','citylist','dislist'));
        }
        if ($goods_id?$model->pcedit($data,$state):$model->pcaddGood($data,$state)) {

            return $this->renderSuccess('更新成功', url('renovation/items'));
        }
        $error = $model->getError() ?: '更新失败';
        return $this->renderError($error);
    }

    /**
     * 评价列表
     */
    public function comment($item_id = null,$user_id = null)
    {
        $info = $this->request->route();
        $model = new \app\common\model\Order();
        $model2 = new \app\common\model\Item();
        if(empty($info['goods_id'])){
            $info['goods_id'] = '';
        }
        $state = 1;
        $list = $model->pcpingjialist($info['goods_id'],$state);
        return $this->fetch('comment', compact('list'));
    }

    /**
     * 软删除
     * @return false|int
     */
    public function setDelete()
    {
        $info = $this->request->post();
        $model = new \app\common\model\Order();
        if($model->setDelete($info['id'])){
        return $this->renderSuccess('成功');
        }
        return $this->renderError('失败');
    }

    /**
     * 订单列表
     */
    public function order($order_no = '')
    {
        $model = new \app\common\model\Order();
        $info = $this->request->post();
        if(empty($info)){
            $info['dataTypead'] = 'All';
        }
        $dataType = $dataTypead =$info['dataTypead'];
        $state = 1;
        $list = $model->pcgetLists($dataTypead, $info,$state,$order_no);
        $title = '全部';
        return $this->fetch('order', compact('title', 'dataType', 'list','dataTypead'));
    }


    /**
     * 订单详情
     * @param $order_id
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function detail()
    {
        $info = $this->request->route();

        $model=new \app\common\model\Order();
        $where['order_id'] = $info['order_id'];
        $detail=$model::detail($info['order_id']);

        return $this->fetch('detail',compact('detail'));

    }

    /*
     * 工地list
     * */
    public function gongdi($name = '')
    {

        $model = new MerchantModel();
        $list = $model->pcgongdilist($name);
        return $this->fetch('gongdilist', compact('list'));
    }

    /*
     * 工地添加
     * */
    public function gongdiadd($merchant_gongdi_id='',$xiangqingm = '')
    {
        $model = new MerchantModel;
        $data=$this->request->post();
        if (!$this->request->isAjax()) {
            $goodsInfo=$model->pcgongdione($merchant_gongdi_id);
            $goodsInfo['gongdi_shelist'] = [];
            if(!empty($goodsInfo['gongdi_she'])){
                $goodsInfo['gongdi_shelist'] = explode(',',$goodsInfo['gongdi_she']);
            }
            $goodsInfo['gongdi_gonglist'] = [];
            if(!empty($goodsInfo['gongdi_gong'])){
                $goodsInfo['gongdi_gonglist'] = explode(',',$goodsInfo['gongdi_gong']);
            }
            //$arr_imge = $model::detailimg($merchant_gongdi_id);
            $Item = new \app\common\model\Item();
            $province = $Item->provinceList();
            $citylist = '';
            if(!empty($goodsInfo['provinceid'])){
                $citylist = $Item->cityList($goodsInfo['provinceid']);
            }
            $dislist='';
            if(!empty($goodsInfo['cityid'])){
                $dislist = $Item->districtList($goodsInfo['cityid']);
            }

            $shejilist = $model->pcshejis($name ='',1);//设计师

            $grenlist = $model->pcshejis($name ='',2);//工人
            if(empty($goodsInfo['provinceid'])){
                $goodsInfo['provinceid'] = '';
            }
            if(empty($goodsInfo['gongdi_zhu'])){
                $goodsInfo['gongdi_zhu'] = '';
            }
            if(empty($goodsInfo['merchant_gongdi_id'])){
                $goodsInfo['merchant_gongdi_id'] = '';
            }
            return $this->fetch('gongdiadd', compact('goodsInfo','xiangqingm','province','citylist','dislist','shejilist','grenlist'));
        }

        if ($merchant_gongdi_id?$model->pcgongdiup($data,$merchant_gongdi_id):$model->pcgongdiadd($data)) {

            return $this->renderSuccess('成功', url('renovation/gongdi'));
        }
        $error = $model->getError() ?: '失败';
        return $this->renderError($error);
    }

    public function gongdidelete($merchant_gongdi_id='')
    {

        $model = new MerchantModel;
        $data=$this->request->post();
        if ($model->pcgongdidelete($data['id'])) {
            return $this->renderSuccess('成功', url('renovation/gongdi'));
        }
        $error = $model->getError() ?: '失败';
        return $this->renderError($error);
    }

    /*
         * 设计师
         * */
    public function shejis($name = '')
    {
        $model = new MerchantModel();
        if(empty($info['types'])){
            $info['types'] = '';
        }
        $list = $model->pcshejis($name,1);
        return $this->fetch('shejislist', compact('list'));
    }

    /*
         * 设计师删除
         * */
    public function shejisdelete($name = '')
    {
        $model = new MerchantModel;
        $data=$this->request->post();
        if ($model->shejisdelete($data['id'])) {
            return $this->renderSuccess('成功', url('renovation/shejis'));
        }
        $error = $model->getError() ?: '失败';
        return $this->renderError($error);
    }

    /*
         * 工人
         * */
    public function gongren($name = '')
    {
        $model = new MerchantModel();
        if(empty($info['types'])){
            $info['types'] = '';
        }
        $list = $model->pcshejis($name,2);
        return $this->fetch('gongrenlist', compact('list'));
    }
    /*
         * 设计师删除
         * */
    public function gongrendelete($name = '')
    {
        $model = new MerchantModel;
        $data=$this->request->post();
        if ($model->shejisdelete($data['id'])) {
            return $this->renderSuccess('成功', url('renovation/gongren'));
        }
        $error = $model->getError() ?: '失败';
        return $this->renderError($error);
    }

    /**
     * 列表
     */
    public function tuandui($name = '')
    {
        $houtai = Session::get('houtaizhuangtai');
        if(!empty($houtai)&&$houtai ==1){
            $where['a.merchant_pid']=self::$user_id;
        }
        if(!empty($name)){
            $where['b.merchant_name']=$name;
        }
        $where['a.state']=1;
        $state = 1;
        $list = (new \app\common\model\MerchantTeam())->pctuanduilist($where,$state);

        return $this->fetch('tuanduilist', compact('list'));
    }

    /**
     * 下级列表
     */
    public function xialists()
    {
        $data = $this->request->post();
        if(empty($data['id'])){
            return $this->renderError('缺少必须参数',1001);
        }
        $where['merchant_id'] = $data['id'];
        $use = new \app\common\model\User();
        $uer = $use->detailShang($where);
        $model = new MerchantTeamModel();
        $list = $model->xialists($data['id']);
        if(!empty($uer['logo'])){
            $uer['logoad'] = '/uploads/'.$uer['logo'].'.jpg';
        }else{
            $uer['logoad'] = '';
        }
        if(count($list)>0){
            foreach ($list as $key=>$value){
                if(!empty($value['logo'])){
                    $list[$key]['logoad'] = '/uploads/'.$value['logo'].'.jpg';
                }else{
                    $list[$key]['logoad'] = '';
                }
            }
        }
        $info['user'] = $uer;
        $info['list'] = $list;
        $info['sum'] = count($list);

        return $this->renderSuccess('成功',$info);
    }
    /*
         * 团队删除
         * */
    public function tuanduidelete()
    {
        $model = (new \app\common\model\MerchantTeam());
        $data=$this->request->post();
        if ($model->shejisdelete($data['id'])) {
            return $this->renderSuccess('成功', url('renovation/tuandui'));
        }
        $error = $model->getError() ?: '失败';
        return $this->renderError($error);
    }

    /*
     * 添加设计师
     * */
    public function addShejis()
    {

        $model = new MerchantModel;
        $info=$this->request->post();
        $goodsInfo ='';
        if (!$this->request->isAjax()) {
            return $this->fetch('addshejis',compact('goodsInfo'));
        }
        if(empty($info['merchant_id'])||empty($info['spec_type'])||empty($info['goods_name'])){
            return $this->renderError('参数不能为空');
        }

        $list = DB::table('bfb_merchant_code')->where(['phone'=>$info['goods_name'],'code'=>$info['spec_type']])->order('create_time','DESC')->find();
        if($list){
            $lists= $model->addTuandui($info,$type='1');
            if($lists){
                return $this->renderSuccess('成功',url('renovation/shejis'));
            }else{
                return $this->renderError('失败');
            }
        }
        return $this->renderError('验证码错误');
    }

    /*
	*手机号拉取验证码
	* @return array
	*/
    public function addYanzm(){
        $model = new MerchantModel;
        $info = $this->request->post();
        if(empty($info['phone'])){
            return $this->renderJson('1004','手机号不能为空');
        }
        $where['a.phone'] = $info['phone'];
        $userone = $model->userOne($where,$info['state']);
        if(!empty($userone))
        {
            //$code = rand('1000','9999');
            $code = '1234';
            $where = ['phone'=>$info['phone'],'code'=>$code,'create_time'=>time()];
            $user=1;//$model->addYanzm($where,$info['phone']);
            if($user == '1002'){
                return $this->renderJson('1002','错误');
            }elseif($user == '1003'){
                return $this->renderJson('1003','验证码15分钟内有效');
            }else{
                return $this->renderJson('1000','发送成功','',$userone);
            }
        }
        return $this->renderJson('1001','该账号下暂无设计师角色');
    }

    /*
    * 添加设计师
    * */
    public function addgongren()
    {

        $model = new MerchantModel;
        $info=$this->request->post();
        $goodsInfo ='';
        if (!$this->request->isAjax()) {
            return $this->fetch('addgongren',compact('goodsInfo'));
        }
        if(empty($info['merchant_id'])||empty($info['spec_type'])||empty($info['goods_name'])){
            return $this->renderError('参数不能为空');
        }

        $list = DB::table('bfb_merchant_code')->where(['phone'=>$info['goods_name'],'code'=>$info['spec_type']])->order('create_time','DESC')->find();
        if($list){
            $lists= $model->addTuandui($info,$type='2');
            if($lists){
                return $this->renderSuccess('成功',url('renovation/gongren'));
            }else{
                return $this->renderError('失败');
            }
        }
        return $this->renderError('验证码错误');
    }

    /**
     * 商品编辑
     */
    public function renovationedit($merchant_id='')
    {
        $model = new \app\common\model\Item();
        $data=$this->request->post();
        $state = '1';
        if (!$this->request->isAjax()) {
            $goodsInfo=Db::table('bfb_merchant')->where(['merchant_id'=>$merchant_id])->find();
            $arr_imge = $model::detailimg($merchant_id);
            // 商品分类
            /*  $itemType = (new TypeModel)->All();
             $brandList = (new ItemModel)->getSortBrands();//获取品牌
             $delivery = DeliveryModel::getAll();*/
            //sku和分类
            $province = $model->provinceList();
            $citylist = '';
            if(!empty($goodsInfo['province_id'])){
                $citylist = $model->cityList($goodsInfo['province_id']);
            }
            $dislist='';
            if(!empty($goodsInfo['city_id'])){
                $dislist = $model->districtList($goodsInfo['city_id']);
            }

            return $this->fetch('renovationedit', compact('goodsInfo','arr_imge','province','citylist','dislist'));
        }

        if($merchant_id){
            $list = Db::table('bfb_merchant')->where(['merchant_id'=>$merchant_id])->update($data);
        }else{
           $info =  Db::table('bfb_merchant_user')->where(['phone'=>$data['phone']])->find($data);
           if($info){
               $data['merchant_user_id'] = $info['merchant_id'];
               $data['state'] = 1;
               $list = Db::table('bfb_merchant')->insert($data);
           }else{
               $asda['phone'] = $data['phone'];
               $asda['password'] = md5($data['phone']);
               $menid =  Db::table('bfb_merchant_user')->insertGetId($asda);
               $data['merchant_user_id'] = $menid;
               $data['state'] = 1;
               $list = Db::table('bfb_merchant')->insert($data);
           }
        }
        if($list){
            return $this->renderSuccess('更新成功', url('renovation/renovation'));
        }
        $error = $model->getError() ?: '更新失败';
        return $this->renderError($error);
    }

}